package net.mohas.docsearch.model.db;

import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Properties;

import net.mohas.docsearch.Constants;

/**
 * This class is used for preparing SQLite database. 
 * If the database file does not exist, it will create database file and open the connection. 
 * If the database file exists, it will only open the connection.
 * 
 * @author Muhammad
 * 
 */
public class SqliteDatabase extends AbstractDatabase {
	
	public static SqliteDatabase instance;
	private static Properties prop;
	
	public static SqliteDatabase getInstance() {
		if (instance == null) {
			instance = new SqliteDatabase();
		}
		return instance;
	}
	
    private SqliteDatabase() {
    	try {
			prop = new Properties();
			prop.load(getClass().getClassLoader().getResourceAsStream(Constants.DB_PROPERTIES_FILE));
			
			connect();
			initDb();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

	@Override
	protected void connect() throws Exception {

		// Load the sqlite-JDBC driver using the current class loader
		Class.forName(prop.getProperty("database.driver"));
		
        try {
        	// Create a database connection
        	connection = DriverManager.getConnection(prop.getProperty("database.url"));
            System.out.println("Successfully open database");
        } catch (Exception e){
            e.printStackTrace();
            throw e;
        }
		
	}
	
	private void initDb() {
		
		try {			
			Statement statement = connection.createStatement();
			statement.addBatch("DROP TABLE IF EXISTS berkas");
			statement.addBatch("CREATE TABLE 'berkas' ('idberkas' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'namaberkas' TEXT NOT NULL, 'lokasiberkas' TEXT NOT NULL, 'status' INTEGER NOT NULL)");

			statement.addBatch("DROP TABLE IF EXISTS df");
			statement.addBatch("CREATE TABLE 'df' ('kata' TEXT NOT NULL, 'df' INTEGER NOT NULL, 'idf' DOUBLE NOT NULL)");
			
			statement.addBatch("DROP TABLE IF EXISTS kata");
			statement.addBatch("CREATE TABLE 'kata' ('kata' TEXT NOT NULL, 'idberkas' INTEGER NOT NULL, 'jumlah' INTEGER NOT NULL, 'tf' DOUBLE NOT NULL, 'bobot' DOUBLE NOT NULL)");
			
			statement.addBatch("DROP TABLE IF EXISTS kueri");
			statement.addBatch("CREATE TABLE 'kueri' ('kata' TEXT NOT NULL, 'jumlah' INTEGER NOT NULL, 'bobot' DOUBLE NOT NULL)");
			
			statement.executeBatch();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		SqliteDatabase.getInstance();
	}
	
}